"use client"

import { useState } from "react"
import { Form, Input, Button, Checkbox, Card, message, Typography } from "antd"
import { UserOutlined, LockOutlined } from "@ant-design/icons"
import { login } from "@/utils/api"
import PropTypes from "prop-types" // 引入 PropTypes
import "./Login.less"

const { Title } = Typography

const Login = ({ onLogin }) => {
  const [loading, setLoading] = useState(false)

  const handleSubmit = async (values) => {
    try {
      setLoading(true)
      // 发送登录请求
      const data = await login(values)

      if (data.success) {
        message.success("登录成功")
        // 调用App组件提供的登录成功处理函数
        onLogin(data.token)
      } else {
        message.error(data.message || "登录失败")
      }
    } catch (error) {
      console.error("登录错误:", error)
      message.error("登录失败，请稍后重试")
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="login-container">
      <div className="login-background" />
      <Card className="login-card">
        <div className="login-header">
          <Title level={2} className="login-title">
            婚礼公司管理系统
          </Title>
          <p className="login-subtitle">优雅高效的婚礼管理平台</p>
        </div>
        <Form
          name="login"
          initialValues={{ remember: true }}
          onFinish={handleSubmit}
          size="large"
          layout="vertical"
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: "请输入用户名" }]}
          >
            <Input prefix={<UserOutlined />} placeholder="用户名" />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: "请输入密码" }]}
          >
            <Input.Password prefix={<LockOutlined />} placeholder="密码" />
          </Form.Item>
          <Form.Item>
            <Form.Item name="remember" valuePropName="checked" noStyle>
              <Checkbox>记住我</Checkbox>
            </Form.Item>
            <a className="login-form-forgot" href="#">
              忘记密码
            </a>
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              className="login-form-button"
              loading={loading}
              block
            >
              登录
            </Button>
          </Form.Item>
        </Form>
        <div className="login-footer">
          <p>© 2024 婚礼公司管理系统</p>
        </div>
      </Card>
    </div>
  )
}

// 添加 propTypes 校验
Login.propTypes = {
  onLogin: PropTypes.func.isRequired,
}

export default Login
